package org.ReportDesigner.converter;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.fop.apps.*;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created with IntelliJ IDEA.
 * User: Kirito
 * Date: 20.02.13
 * Time: 20:26
 * To change this template use File | Settings | File Templates.
 */
public class Convert {

    private static final Logger log = Logger.getLogger(Convert.class);
    private File inXMLFile = new File("D:\\intellij Idea workspase\\renderer\\src\\primerfayla.xml");
    //private File outXMLFile = new File("D:\\intellij Idea workspase\\renderer\\src\\primerfayla.xml");
    private File outPDFFile;
    private File confFile;
    private File xlsFoFile;

    public Convert(){
    }

    public Convert(File inXMLFile, File outPDFFile){
        this.inXMLFile = inXMLFile;
        this.outPDFFile = outPDFFile;
    }

    public Convert(File inXMLFile, File outPDFFile, File confFile){
        this.inXMLFile = inXMLFile;
        this.outPDFFile = outPDFFile;
        this.confFile = confFile;
    }

    public void setInXMLFile(File inXMLFile) {
        this.inXMLFile = inXMLFile;
    }

    public void setOutPDFFile(File outPDFFile) {
        this.outPDFFile = outPDFFile;
    }

    public void setConfFile(File confFile) {
        this.confFile = confFile;
    }



    private void   structureAnalysis(){

    }


    public void convertToPDF() throws IOException, FOPException, TransformerException {

        FileInputStream in = new FileInputStream(inXMLFile);
        FileChannel channel = in.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
        channel.read(byteBuffer);
        byteBuffer.rewind();
        channel.close();
        in.close();
        String name = inXMLFile.getName();
        name = name.substring(0, name.length() - 4);
        outPDFFile = new File(inXMLFile.getParent() + "\\" + name + ".pdf");
        StreamSource xmlSource =
                new StreamSource(new ByteArrayInputStream( byteBuffer.array()));

        OutputStream out = new FileOutputStream(outPDFFile);
        //файл xls-fo преобразования
        File xslFile = new File("D:\\intellij Idea workspase\\renderer\\src\\" +
                "main\\java\\com\\vsu\\renderer\\converters\\transform.xsl");
        // Указание источника для страницы стилей
        FileInputStream xslFileStream = new FileInputStream(xslFile);
        StreamSource xslSource = new StreamSource(xslFileStream);

        // Получение XSL-процессора
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transformer = tfactory.newTransformer(xslSource);

        // Настройка процессора FOP
        DefaultConfigurationBuilder dConfigurationBuilder = new DefaultConfigurationBuilder();
        try {
            Configuration configuration = dConfigurationBuilder.buildFromFile( new File(
                    "D:\\intellij Idea workspase\\renderer\\src\\main\\sources\\userconfig"));

            FopFactory fopFactory = FopFactory.newInstance();
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            foUserAgent.setProducer(this.getClass().getName());
            fopFactory.setUserConfig(configuration);
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent);



            // Выполнение преобразования
            Result res = new SAXResult(fop.getDefaultHandler());
            transformer.transform(xmlSource, res);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        channel.close();
        out.close();

    }

    public File getXMLFile() throws FileNotFoundException {
        if (inXMLFile.exists()) return inXMLFile;
        else {
            throw new FileNotFoundException();
        }
    }

    public File getPDFFile() throws FileNotFoundException {
        if (outPDFFile.exists()) return outPDFFile;
        else {
            throw new FileNotFoundException();
        }
    }


}
